package com.steven.im;

import android.annotation.SuppressLint;
import android.app.Application;
import android.content.Context;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.common.OSSLog;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.mob.MobSDK;
import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.FormatStrategy;
import com.orhanobut.logger.Logger;
import com.orhanobut.logger.PrettyFormatStrategy;
import com.steven.im.base.Constant;
import com.steven.im.utils.FileUtils;
import com.steven.im.utils.SPUtils;
import com.steven.im.utils.SystemUtils;
import com.steven.im.utils.UserUtils;
import com.steven.im.webSocket.WebSocketClient;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.commonsdk.UMConfigure;

import org.litepal.LitePal;

public class App extends Application {
    @SuppressLint("StaticFieldLeak")
    private static Context mContext;
    public static Application myApplication;
    // IWXAPI 是第三方app和微信通信的openApi接口
    private static IWXAPI api;

    //    //阿里OOS服务
    private static OSS oss;

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this;
        myApplication = this;
        //创建应用目录
        FileUtils.createAppDir();
        initLogger();
        //注册微信服务
        regToWx();
        //获取header信息
        getGlobalHeader();
        //ShareSDK
        MobSDK.init(this);
        //友盟
        UMConfigure.init(this, UMConfigure.DEVICE_TYPE_PHONE, "");
        //进行检测 用户是否已经退出登录
        if (UserUtils.checkLogin()){
            WebSocketClient.getInstance().connectAsynchronously();
        }
        //初始化数据库
        LitePal.initialize(this);
    }

    //获取上下文对象
    public static Context getContext() {
        return mContext;
    }

    //初始化logger日志输出
    private void initLogger() {
        FormatStrategy formatStrategy = PrettyFormatStrategy.newBuilder()
                .showThreadInfo(false)  //是否选择显示线程信息，默认为true
                .tag("spellGroup")   //自定义TAG全部标签，默认PRETTY_LOGGER
                .build();
        //deBug模式下日志正常打开  release下会自动关闭
        Logger.addLogAdapter(new AndroidLogAdapter(formatStrategy) {
            @Override
            public boolean isLoggable(int priority, String tag) {
                return BuildConfig.DEBUG;
            }
        });

    }

    /**
     * 获取 全局请求头变量
     */
    private void getGlobalHeader() {
        SPUtils.put(mContext, "OSType", SystemUtils.getOSType()); //手机系统版本(iOS, Android)
        SPUtils.put(mContext, "OSVersion", SystemUtils.getOSVersion());//手机系统版本号
        SPUtils.put(mContext, "deviceModel", SystemUtils.getDeviceModel());//手机型号
        SPUtils.put(mContext, "uniqueIdentifier", SystemUtils.getUniqueIdentifier(mContext));//唯一标识
        SPUtils.put(mContext, "appVersion", SystemUtils.getLocalVersion(mContext) + "");//获取应用版本号
    }

    /**
     * 注册微信服务  Constant.WxInfo.WX_APPID
     */
    private void regToWx() {
        api = WXAPIFactory.createWXAPI(this, Constant.WxInfo.WX_APPID, false);
        api.registerApp(Constant.WxInfo.WX_APPID);
    }

    /**
     * 获取微信API
     *
     * @return
     */
    public static IWXAPI getWXAPI() {
        return api;
    }


    /**
     * 阿里OSS服务
     */
    public void initOSSService() {
        final String keyId = SPUtils.get(getContext(), Constant.AliOOS.KEY_ID, "").toString();
        final String keySecret = SPUtils.get(getContext(), Constant.AliOOS.KEY_SECRET, "").toString();
        final String endPoint = SPUtils.get(getContext(), Constant.AliOOS.END_POINT, "").toString();
        try {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(
                            keyId, keySecret);
                    ClientConfiguration conf = new ClientConfiguration();
                    conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
                    conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
                    conf.setMaxConcurrentRequest(8); // 最大并发请求数，默认5个
                    conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次
                    OSSLog.enableLog();
                    oss = new OSSClient(getApplicationContext(), endPoint, credentialProvider, conf);
                }
            }).start();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 获取OSS的引用
     */
    public static OSS getOSS() {
        return oss;
    }

}
